﻿using KINLO.Model;
using KINLO.Model.InfoModel;
using KINLO.UI.Main.Hepler;
using KINLO.UI.Main.Services;
using KINLO.MES;
using KINLO.MES.MESMachineVoid;
using KINLO.MES.MESModels;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using KINLO.WebApi.MESModels;
using System.Reflection;
using System.Web.UI.WebControls;
using System.Threading;
using NPOI.SS.Formula.Functions;
using NPOI.XSSF.Streaming.Values;
using GalaSoft.MvvmLight.Messaging;
using System.Diagnostics;
using KINLO.Model.MES;
using ControlzEx.Standard;
using HandyControl.Controls;

namespace KINLO.UI.Main.MES
{
    public class InjectMes
    {
        //private static int deviceStatus = 1;
        //private static object lockObject = new object();
        /// <summary>
        /// 注液生产数据上传
        /// </summary>
        /// <param name="batt"></param>
        /// <returns></returns>
        public static int MESProductUpLoad(Weight batt,Counter count)
        {
            try
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                var msgmes = string.Format($"MES工艺参数开始上传");
                Messenger.Default.Send(msgmes, "ReceiveEventInfo");

                MESInjectModel1 data = new MESInjectModel1();
                data.Team = InfoDataModel.Tmp.ClassTeam;
                data.Shift = InfoDataModel.Tmp.Class;
                data.EquipmentCode = InfoDataModel.Tmp.EquipmentCode;
                data.WorkOrderNo = InfoDataModel.Tmp.WorkOrder;
                data.Operator = InfoDataModel.Tmp.UserName;
                data.EquipmentStatus = InfoDataModel.Tmp.status;
                data.TrayNum = batt.StationNo.HasValue? batt.StationNo.ToString():"0";
                data.Code = "0";
                data.TrayIndex = batt.RowNo.HasValue ? batt.RowNo.ToString() : "0";
                data.TrayCol = batt.Index.ToString();
                data.ZhuYe_Parameters5 = "0";
                data.ZhuYe_Parameters6 = "0";
                data.BeforWeight_One = batt.FInjectionWeight.HasValue ? batt.FInjectionWeight.ToString() : "0";
                data.AfterWeight_One = batt.BInjectionWeight.HasValue ? batt.BInjectionWeight.ToString() : "0";
                data.InjectionNum_One = batt.InjectionWeight.HasValue ? batt.InjectionWeight.ToString() : "0";

                data.NG1 = count.LeakHuntingNgCount.ToString();
                data.NG2 = count.WeightNgCount.ToString();
                data.AcquisitionTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");


                //补液量
                var repairInjectionData = (ushort)Math.Ceiling((double)(batt.TheoryRepairValue.HasValue? batt.TheoryRepairValue * 10 : 0));
                double repairInjection = 0;
                //补液量1-5补0.4，5-9补0.8，大于等于10 NG电池不用补
                if (repairInjectionData > 0 && repairInjectionData <= 5)
                {
                    repairInjection = 0.4;
                }
                else if (repairInjectionData > 5 && repairInjectionData <= 9)
                {
                    repairInjection = 0.8;
                }
                data.SupplementNum_One = repairInjection.ToString();
                data.ZhuYe_Parameters7 = batt.LeakHuntingResult == 0 ? "NG" : "OK";
                data.ZhuYe_Parameters8 = batt.OrderNo.ToString();
                data.ZhuYe_Parameters9 = batt.OrderNo2.ToString();
                data.InjStation = batt.OrderNo2.ToString();
                data.BracketNumber = batt.TrayCode;

                var result = InjectWebApi.MESProductData(data);
                // 停止计时
                stopwatch.Stop();
              
               Messenger.Default.Send($"上传MES耗时：{stopwatch.ElapsedMilliseconds}", "ReceiveEventInfo");
                return result;
            }
            catch (Exception ex)
            {
                var msgmes = string.Format($"MES工艺参数上传失败：{ex.ToString()}");
                Messenger.Default.Send(msgmes, "ReceiveEventInfo");
                return -1;
            }
        }

        /// <summary>
        /// 和MES标准工艺参数对比
        /// </summary>
        /// <param name="batt"></param>
        /// <returns></returns>
        public static void CompareStandardProcess(Weight batt)
        {
            try
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                MESStandardProcess data = new MESStandardProcess();
                data.BeforWeight_One = batt.FInjectionWeight.HasValue ? batt.FInjectionWeight.HasValue.ToString():"0";
                data.AfterWeight_One = batt.BInjectionWeight.HasValue ? batt.BInjectionWeight.HasValue.ToString():"0";
                data.InjectionNum_One = batt.InjectionWeight.HasValue ? batt.InjectionWeight.HasValue.ToString() : "0";
                data.ZhuYe_Parameters7 = batt.LeakHuntingResult.HasValue ? batt.LeakHuntingResult.HasValue.ToString() : "0";
                var repairInjectionData = (ushort)Math.Ceiling((double)(batt.TheoryRepairValue.HasValue ? batt.TheoryRepairValue * 10 : 0));
                double repairInjection = 0;
                //补液量1-5补0.4，5-9补0.8，大于等于10 NG电池不用补
                if (repairInjectionData > 0 && repairInjectionData <= 5)
                {
                    repairInjection = 0.4;
                }
                else if (repairInjectionData > 5 && repairInjectionData <= 9)
                {
                    repairInjection = 0.8;
                }
                data.SupplementNum_One = repairInjection.ToString();


                MESParmLimitModel mesParmLimitData = new MESParmLimitModel();
                mesParmLimitData.parentvo = new Parentvo() { EquipmentCode = InfoDataModel.Tmp.EquipmentCode };
                mesParmLimitData.childrenvo = new List<Childrenvo>();

                var generalData = InfoDataModel.Tmp.GeneralData;
                if(generalData!=null&& generalData.Count>0)
                {
                    foreach (var item in generalData)
                    {
                        string propertyName = item.ParameterCode; // 获取参数编码作为属性名
                                                                  //如果是测漏值就不用对比，因为只有测漏ok或者NG，0是NG，1是OK，NG则调用超限接口
                        if (propertyName != null && propertyName == "ZhuYe_Parameters7")
                        {
                            if (data.ZhuYe_Parameters7 == "1")
                            {
                                mesParmLimitData.childrenvo.Add(
                                      new Childrenvo()
                                      {
                                          parameterName = item.ParameterName,
                                          parameterCode = item.ParameterCode,
                                          ActualValue = data.ZhuYe_Parameters7,
                                          standardValue = item.StandardValue,
                                          upperValue = item.UpperValue,
                                          lowerValue = item.LowerValue,
                                          CreatTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                          StepCode = item.StepCode,
                                          StepName = item.StepName,
                                      });
                            }
                            continue;
                        }
                        PropertyInfo propertyInData = data.GetType().GetProperty(propertyName); // 在中工艺参数中查找属性
                        if (propertyInData != null)
                        {
                            string valueToCompare = propertyInData.GetValue(data)?.ToString();   // 假设你要比较的值

                            if (string.IsNullOrWhiteSpace(valueToCompare))
                            {
                                continue;
                            }
                            double value = double.Parse(valueToCompare);        //转成双精度小数

                            if (value <= 0)
                            {
                                continue;
                            }

                            bool isNg = false;
                            if (!string.IsNullOrEmpty(item.UpperValue) && !string.IsNullOrEmpty(item.LowerValue))
                            {
                                // 既有上限值又有下限值的情况
                                double upper = double.Parse(item.UpperValue);
                                double lower = double.Parse(item.LowerValue);


                                if (value < lower || value > upper)
                                {
                                    isNg = true;

                                    //$"[{_data.MachineName}]MES参数{item.ParameterName}不在上下限范围内,\r\nMES上限值：{upper}，MES下限值：{lower}，生产值：{value}".Info();
                                }
                                //Console.WriteLine("不在上下限范围内");
                            }
                            else if (!string.IsNullOrEmpty(item.LowerValue))
                            {
                                // 只有下限值的情况
                                double lower = double.Parse(item.LowerValue);

                                if (value < lower)
                                {
                                    isNg = true;
                                    //$"[{_data.MachineName}]MES参数{item.ParameterName}低于下限, MES下限值：{lower}，生产值：{value}".Info();
                                }
                                //Console.WriteLine("低于下限");
                            }
                            else if (!string.IsNullOrEmpty(item.UpperValue))
                            {
                                // 只有上限值的情况
                                double upper = double.Parse(item.UpperValue);

                                if (value > upper)
                                {
                                    isNg = true;
                                    //$"[{_data.MachineName}]MES参数{item.ParameterName}超出上限,MES上限值：{upper}，生产值：{value}".Info();
                                }
                                //Console.WriteLine("超出上限");

                            }
                            else if (!string.IsNullOrEmpty(item.StandardValue))
                            {
                                // 只有标准值的情况
                                double standard = double.Parse(item.StandardValue);

                                if (value != standard)
                                {
                                    isNg = true;
                                    //$"[{_data.MachineName}]MES参数{item.ParameterName}不等于标准值,MES标准值：{standard}，生产值：{value}".Info();
                                }
                            }
                            if (isNg)
                            {
                                mesParmLimitData.childrenvo.Add(
                                        new Childrenvo()
                                        {
                                            parameterName = item.ParameterName,
                                            parameterCode = item.ParameterCode,
                                            ActualValue = value.ToString(),
                                            standardValue = item.StandardValue,
                                            upperValue = item.UpperValue,
                                            lowerValue = item.LowerValue,
                                            CreatTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                            StepCode = item.StepCode,
                                            StepName = item.StepName,
                                        });
                            }

                        }
                    }

                    if (mesParmLimitData.childrenvo.Count > 0)
                    {
                        //调用参数超限接口
                        GeneralWebApi.MESParmLimit(InfoDataModel.Tmp.Url7, mesParmLimitData);
                    }
                }
               

                // 停止计时
                stopwatch.Stop();

                Messenger.Default.Send($"MES工艺标准对比耗时：{stopwatch.ElapsedMilliseconds}", "ReceiveEventInfo");

            }
            catch (Exception ex)
            {
                var msgmes = string.Format($"标准工艺参数对比失败：{ex.ToString()}");
                Messenger.Default.Send(msgmes, "ReceiveEventInfo");
            }
        }
        /// <summary>
        /// 注液生产统计上传
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        public static int MESCountUpLoad(CountModel count)
        {
            try
            {
                MESProductDataModel data = new MESProductDataModel();
                data.Team = InfoDataModel.Tmp.ClassTeam;
                data.Shift = InfoDataModel.Tmp.Class;
                data.WorkNumber = InfoDataModel.Tmp.UserName;
                data.EquipmentNo = InfoDataModel.Tmp.EquipmentCode;
                data.WorkOrderNo = InfoDataModel.Tmp.WorkOrder;
                data.PutIntoNumber = count.InCount.ToString();
                data.QualifiedNumber = count.OkCount.ToString();
                data.UnqualifiedNumber = count.NgCount.ToString();
                //var mesresult = GeneralWebApi.MESProductCountData(InfoDataModel.Tmp.Url1, data);
                //return mesresult;
                return 0;
            }
            catch (Exception ex)
            {
                return -1;
            }
        }
        /// <summary>
        /// 注液设备报修上传
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static int MESEquipmentMaintain()
        {
            try
            {
                MESEquipmentMaintainModel data = new MESEquipmentMaintainModel();
                data.EquipmentCode = InfoDataModel.Tmp.EquipmentCode;
                data.UserName = InfoDataModel.Tmp.UserName;
                return GeneralWebApi.MESEquipmentMaintain(InfoDataModel.Tmp.Url2, data);
            }
            catch (Exception ex)
            {
                return -1;
            }
        }
        /// <summary>
        /// 注液设备履历上传
        /// </summary>
        /// <param name="status"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        public static int MESEquipmentStatus(List<MESEquipmentStatusModel> statusmodel)
        {
            try
            {

                //MESEquipmentStatusModel data = new MESEquipmentStatusModel();
                //data.EquipmentCode = InfoDataModel.Tmp.EquipmentCode;
                //data.State_Code = statusmodel.Status.ToString();
                //data.Beg_time = statusmodel.StartTime.ToString("yyyy-MM-dd HH:mm:ss");
                //data.End_time = statusmodel.EndTime.ToString("yyyy-MM-dd HH:mm:ss");
                //data.St_seconds = (statusmodel.EndTime - statusmodel.StartTime).TotalSeconds.ToString();
                //data.St_ResonCode = statusmodel.ReasonCode.ToString();
                return GeneralWebApi.MESEquipmentStatus(InfoDataModel.Tmp.Url3, statusmodel);
            }
            catch (Exception ex)
            {
                return -1;
            }
        }


        /// <summary>
        /// 注液设备获取工单
        /// </summary>
        /// <param name="Eqcode"></param>
        /// <returns></returns>
        public static List<ResultData> MESGetWorkOrder(string Eqcode, string process_id)
        {
            try
            {
                MESWorkOrderModel data = new MESWorkOrderModel();
                data.equipment_id = Eqcode;
                data.process_id = process_id;
                var returndata = GeneralWebApi.MESWorkOrder(InfoDataModel.Tmp.Url5, data);
                if (returndata != null)
                {
                    var getdata = JsonConvert.DeserializeObject<MESWorkOrderReturnModel>(returndata.ToString());
                    if (getdata.success && getdata.statusCode == "200")
                    {
                        return getdata.resultData;
                    }
                    else
                    {
                        return null;

                    }
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 注液设备工号验证
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public static int MESUserNameCheck(string username)
        {
            try
            {
                MESWorkNameModel data = new MESWorkNameModel();
                data.WorkNumber = username;
                return GeneralWebApi.MESUserNameCheck(InfoDataModel.Tmp.Url6, data);
            }
            catch (Exception ex)
            {
                return -1;
            }
        }

        /// <summary>
        /// 注液参数超限接口
        /// </summary>
        /// <returns></returns>
        public static int MESParmLimit()
        {
            try
            {
                MESParmLimitModel data = new MESParmLimitModel();
                Parentvo parentvo = new Parentvo();
                parentvo.EquipmentCode = InfoDataModel.Tmp.EquipmentCode;
                Childrenvo childrenvo = new Childrenvo();
                data.parentvo = parentvo;
                data.childrenvo.Add(childrenvo);
                GeneralWebApi.MESParmLimit(InfoDataModel.Tmp.Url7, data);
                return 1;
            }
            catch (Exception ex)
            {
                return -1;
            }
        }

        /// <summary>
        /// 生产统计上传 小时
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        public static int MESCountUpLoad_Hour(CountModel tmp)
        {
            try
            {
                RootMESProduct_HourDataModel root = new RootMESProduct_HourDataModel();
                List<MESProduct_HourDataModel> datas = new List<MESProduct_HourDataModel>();
                MESProduct_HourDataModel data = new MESProduct_HourDataModel();
                data.Team = InfoDataModel.Tmp.ClassTeam;
                data.Shift = InfoDataModel.Tmp.Class;
                data.WorkNumber = InfoDataModel.Tmp.UserName;
                data.EquipmentNo = InfoDataModel.Tmp.EquipmentCode;
                data.WorkOrderNo = InfoDataModel.Tmp.WorkOrder;
                data.PutIntoNumber = tmp.InCount.ToString();
                data.QualifiedNumber = tmp.OkCount.ToString();
                data.UnqualifiedNumber = tmp.NgCount.ToString();
                data.ProductionStartTime = DateTime.Now.AddHours(-1).ToString("yyyy-MM-dd HH:mm:ss");
                data.ProductionEndTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                datas.Add(data);
                root.data = datas;

                //var mesresult =-1;
                var mesresult = GeneralWebApi.MESProductCountDataa_Hour(InfoDataModel.Tmp.Url9, root);

                if (mesresult != 1)
                {
                    Messenger.Default.Send(data, "HourData");
                }
                return mesresult;
            }
            catch (Exception ex)
            {
                return -1;
            }
        }
        /// <summary>
        /// 生产统计上传 天
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        public static int MESCountUpLoad_Day(CountModel tmp)
        {
            try
            {
                RootMESProduct_DayDataModel root = new RootMESProduct_DayDataModel();
                List<MESProduction_DayDataModel> datas = new List<MESProduction_DayDataModel>();
                MESProduction_DayDataModel data = new MESProduction_DayDataModel();
                data.Team = InfoDataModel.Tmp.ClassTeam;
                data.Shift = InfoDataModel.Tmp.Class;
                data.WorkNumber = InfoDataModel.Tmp.UserName;
                data.EquipmentNo = InfoDataModel.Tmp.EquipmentCode;
                data.WorkOrderNo = InfoDataModel.Tmp.WorkOrder;
                data.PutIntoNumber = tmp.InCount.ToString();
                data.QualifiedNumber = tmp.OkCount.ToString();
                data.UnqualifiedNumber = tmp.NgCount.ToString();
                datas.Add(data);
                root.data = datas;
                //var mesresult = -1;
                var mesresult = GeneralWebApi.MESProductCountData_Day(InfoDataModel.Tmp.Url10, root);
                if (mesresult != 1)
                {
                    Messenger.Default.Send(data, "DayData");
                }
                return mesresult;
            }
            catch (Exception ex)
            {
                return -1;
            }
        }

        /// <summary>
        ///  生产统计上传 天 补录
        /// </summary>
        /// <param name="tmp"></param>
        /// <returns></returns>
        public static int MESCountAddRec_Day(MESProduction_DayDataModel data)
        {
            try
            {
                RootMESProduct_DayDataModel root = new RootMESProduct_DayDataModel();
                List<MESProduction_DayDataModel> datas = new List<MESProduction_DayDataModel>();
              
                datas.Add(data);
                root.data = datas;
                var mesresult = GeneralWebApi.MESProductCountData_Day(InfoDataModel.Tmp.Url10, root);
                return mesresult;
            }
            catch (Exception ex)
            {
                return -1;
            }
        }

        /// <summary>
        ///  生产统计上传 小时 补录
        /// </summary>
        /// <param name="tmp"></param>
        /// <returns></returns>
        public static int MESCountAddRec_Hour(MESProduct_HourDataModel data)
        {
            try
            {
                RootMESProduct_HourDataModel root = new RootMESProduct_HourDataModel();
                List<MESProduct_HourDataModel> datas = new List<MESProduct_HourDataModel>();
              
                datas.Add(data);
                root.data = datas;
                var mesresult = GeneralWebApi.MESProductCountDataa_Hour(InfoDataModel.Tmp.Url9, root);

                return mesresult;
            }
            catch (Exception ex)
            {
                return -1;
            }
        }

        /// <summary>
        /// 获取标准参数
        /// </summary>
        /// <returns></returns>
        public static List<MESGeneralDataReturnModel> MESSecondsData()
        {
            try
            {
                MESGeneralDataModel data = new MESGeneralDataModel();
                data.WorkOrderId = InfoDataModel.Tmp.WorkOrder;
                data.EquipmentCode = InfoDataModel.Tmp.EquipmentCode;
                var returndata = GeneralWebApi.MESGeneralData(InfoDataModel.Tmp.Url4, data);
                if (returndata != null)
                {
                    var getdata = JsonConvert.DeserializeObject<List<MESGeneralDataReturnModel>>(returndata.ToString());
                    return getdata;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                return null;
            }

        }

    }
}
